<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form label-position="right" :model="parkingChargeForm" :label-width="formLabelWidth" ref="parkingChargeFormRef" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="车位号" prop="parkingAreaNumber">
              <el-input v-model="parkingChargeForm.parkingAreaNumber" placeholder="请选择车位号" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findParkingArea"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="单元房号" prop="residentRoomNumber">
              <el-input v-model="parkingChargeForm.residentRoomNumber" placeholder="请选择单元房号" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findRoom"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="车牌" prop="licensePlate">
              <el-input v-model="parkingChargeForm.licensePlate" placeholder="请输入车牌" maxlength="32"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="使用开始时间" prop="billingStartDate">
              <el-date-picker
                  v-model="parkingChargeForm.billingStartDate" type="date" placeholder="使用开始时间" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="使用结束时间" prop="billingEndDate">
              <el-date-picker
                  v-model="parkingChargeForm.billingEndDate" type="date" placeholder="使用结束时间" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="金额" prop="amount">
              <el-input-number v-model="parkingChargeForm.amount" :min="1" :max="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="parkingChargeForm.remark" placeholder="请输入备注" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onSave">保存</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="parkingAreaSelectorVisible" v-if="parkingAreaSelectorVisible" title="车位信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <parking-area-selector @parking-area-selected-event="handleParkingAreaSelectedEvent">
      </parking-area-selector>
    </el-dialog>
    <el-dialog v-model="roomSelectorVisible" v-if="roomSelectorVisible" title="单元信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <room-selector @room-selected-event="handleRoomSelectedEvent">
      </room-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {defineEmits, defineProps, inject, onMounted, reactive, ref, toRefs} from 'vue';
import parkingChargeApi from '@/api/parkingChargeApi'
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {ParkingChargeForm} from "@/types/req/parkingChargeForm";
import type {Result} from '@/types/result'
import type {ParkingCharge} from "@/types/resp/parkingCharge";
import type {Id} from "@/types/id";
import { Search } from '@element-plus/icons-vue';
import ParkingAreaSelector from "@/views/parkingArea/ParkingAreaSelector.vue";
import RoomSelector from "@/views/room/RoomSelector.vue";

const props = defineProps<Id>()
const parkingChargeFormRef = ref<FormInstance | null>(null);
const parkingChargeForm = reactive<ParkingChargeForm>({
  parkingAreaId: 0,
  parkingAreaNumber: '',
  residentRoomId: 0,
  residentRoomNumber: '',
  licensePlate: '',
  billingStartDate: '',
  billingEndDate: '',
  amount: 0,
  remark: '',
})
const parkingAreaSelectorVisible = ref<boolean>(false)
const roomSelectorVisible = ref<boolean>(false)
const emit = defineEmits<{
  (e: 'resetParkingChargeAddEvent'): void;
  (e: 'closeParkingChargeAddEvent', data?: { search: boolean }): void;
}>()

const rules = reactive({
  parkingAreaNumber: [
    { required: true, message: '请输入车位号', trigger: 'blur' }
  ],
  residentRoomNumber: [
    { required: true, message: '请输入单元房号', trigger: 'blur' }
  ],
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  if (props.id) {
    initParkingChargeFormById(props.id)
  }
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const initParkingChargeFormById = async (id: number) => {
  const resp: Result<ParkingCharge> = await parkingChargeApi.findById(id)
  if (resp && resp.code === 1 && resp.data) {
    Object.assign(parkingChargeForm, resp.data)
  }
}

const onReset = () => {
  if (parkingChargeFormRef.value) {
    parkingChargeFormRef.value.resetFields()
  }
  emit('resetParkingChargeAddEvent')
}

const onSave = () => {
  if (!parkingChargeFormRef.value) {
    return
  }
  parkingChargeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const resp: Result<void> = await parkingChargeApi.save(parkingChargeForm)
      if (resp && resp.code === 1) {
        ElMessage.success('保存成功')
        emit('closeParkingChargeAddEvent', {search: true})
      } else {
        ElMessage.error('保存失败:' + (resp.msg ? resp.msg : ''))
      }
    }
  })
}

const findParkingArea = () => {
  parkingAreaSelectorVisible.value = true
}

const handleParkingAreaSelectedEvent = (selectedParkingArea: any) => {
  parkingAreaSelectorVisible.value = false
  if (selectedParkingArea && 'parkingAreaId' in selectedParkingArea && parkingChargeForm.parkingAreaId !== selectedParkingArea['parkingAreaId']) {
    parkingChargeForm.parkingAreaId = selectedParkingArea['parkingAreaId']
    parkingChargeForm.parkingAreaNumber = selectedParkingArea['parkingAreaNumber']
  }
}

const findRoom = () => {
  roomSelectorVisible.value = true
}

const handleRoomSelectedEvent = (selectedRoom: any) => {
  roomSelectorVisible.value = false
  if (selectedRoom && 'residentRoomId' in selectedRoom && parkingChargeForm.residentRoomId !== selectedRoom['residentRoomId']) {
    parkingChargeForm.residentRoomId = selectedRoom['residentRoomId']
    parkingChargeForm.residentRoomNumber = selectedRoom['residentRoomNumber']
  }
}

const onBack = () => {
  emit('closeParkingChargeAddEvent')
}
</script>

<style lang="scss">
</style>
